<template>
    <div class="reader-manage">
        <div class="toolbar">
            <el-input v-model="search" placeholder="搜索姓名/账号" style="width:240px;margin-right:12px;" clearable
                @keyup.enter="onSearch" />
            <el-button type="success" class="search-btn" @click="onSearch" style="margin-right:12px;">搜索</el-button>
            <el-button type="primary" @click="onAdd">新增读者</el-button>
            <el-button color="blue" @click="onExportExcel" style="margin-left:8px;">导出Excel</el-button>
        </div>
        <el-table :data="pagedReaders" style="width:100%;margin-top:16px;" border stripe :loading="tableLoading"
            ref="readerTable" height="500px"
            :header-cell-style="{ textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }"
            :cell-style="{ textAlign: 'center' }" fixed-header>
            <el-table-column type="selection" width="40" :selectable="selectableReader" />
            <el-table-column prop="name" label="姓名" min-width="100" fixed="left" />
            <el-table-column prop="username" label="账号" min-width="100" />
            <el-table-column prop="phone" label="手机号" min-width="120" />
            <el-table-column prop="email" label="邮箱" min-width="160" />
            <el-table-column prop="status" label="状态" min-width="80">
                <template #default="scope">
                    <el-tag :type="scope.row.status === '正常' ? 'success' : 'info'">{{ scope.row.status }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="gender" label="性别" min-width="60">
                <template #default="scope">
                    {{ scope.row.gender === 1 || scope.row.gender === '1' || scope.row.gender === '男' ? '男' : '女' }}
                </template>
            </el-table-column>
            <el-table-column label="操作" min-width="140" fixed="right">
                <template #default="scope">
                    <el-button size="small" @click="onEdit(scope.row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="onDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div style="margin:16px 0;display:flex;align-items:center;">
            <el-button type="danger" size="small" :disabled="multipleSelection.length === 0"
                @click="onBatchDelete">批量删除</el-button>
            <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="[10, 20, 50]"
                :total="readers.length" layout="total, sizes, prev, pager, next, jumper" style="margin-left:auto;"
                @current-change="onPageChange" @size-change="onPageSizeChange" background prev-text="上一页"
                next-text="下一页" />
        </div>
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑读者' : '新增读者'" width="400px">
            <el-form :model="editForm" label-width="80px">
                <el-form-item label="姓名" required>
                    <el-input v-model="editForm.name" />
                </el-form-item>
                <el-form-item label="账号" required>
                    <el-input v-model="editForm.username" />
                </el-form-item>
                <el-form-item label="手机号" required>
                    <el-input v-model="editForm.phone" />
                </el-form-item>
                <el-form-item label="邮箱">
                    <el-input v-model="editForm.email" />
                </el-form-item>
                <el-form-item label="状态" required>
                    <el-select v-model="editForm.status">
                        <el-option label="正常" value="正常" />
                        <el-option label="禁用" value="禁用" />
                    </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="editForm.gender">
                        <el-radio :value="'男'">男</el-radio>
                        <el-radio :value="'女'">女</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="密码" :required="!isEdit">
                    <el-input v-model="editForm.password" type="password" autocomplete="new-password"
                        :placeholder="isEdit ? '如需修改请填写' : '请输入密码'" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as XLSX from 'xlsx'

const readers = ref([])
const search = ref('')
const dialogVisible = ref(false)
const editForm = ref({})
const isEdit = ref(false)
const tableLoading = ref(false)
const multipleSelection = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const readerTable = ref(null)
// 多选时仅允许“正常”状态
const selectableReader = (row) => row.status === '正常'
// 导出Excel
const onExportExcel = () => {
    if (!readers.value || readers.value.length === 0) {
        ElMessage.warning('没有可导出的读者数据')
        return
    }
    const genderText = (g) => {
        if (g === 1 || g === '1' || g === '男' || g === 'male' || g === '男生') return '男'
        if (g === 0 || g === '0' || g === '女' || g === 'female' || g === '女生') return '女'
        if (typeof g === 'string' && g.includes('男')) return '男'
        if (typeof g === 'string' && g.includes('女')) return '女'
        return ''
    }
    const data = readers.value.map(r => ({
        姓名: r.name,
        账号: r.username,
        性别: genderText(r.gender),
        电话: r.phone,
        状态: r.status
    }))
    const ws = XLSX.utils.json_to_sheet(data)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '读者列表')
    XLSX.writeFile(wb, `读者列表_${new Date().toISOString().slice(0, 10)}.xlsx`)
}
const pagedReaders = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value
    return readers.value.slice(start, start + pageSize.value)
})
const fetchReaders = async (keyword = '') => {
    tableLoading.value = true
    let url = '/readers'
    if (keyword) {
        const res = await axios.get(url)
        readers.value = res.data.filter(r =>
            r.name.includes(keyword) ||
            r.username.includes(keyword) ||
            r.phone.includes(keyword)
        )
    } else {
        const res = await axios.get(url)
        readers.value = res.data
    }
    tableLoading.value = false
    currentPage.value = 1
}

onMounted(() => {
    fetchReaders()
})

const onSearch = () => {
    fetchReaders(search.value)
}
const onAdd = () => {
    editForm.value = {
        name: '',
        username: '',
        gender: '男', // 新增默认男
        phone: '',
        status: '正常',
        role: 'reader', // 必须补全
        password: ''
    }
    isEdit.value = false
    dialogVisible.value = true
}
const onEdit = (row) => {
    // 深拷贝row，性别字段转换
    let gender = row.gender
    if (gender === 1 || gender === '1' || gender === '男' || gender === 'male' || gender === '男生') gender = '男'
    else if (gender === 0 || gender === '0' || gender === '女' || gender === 'female' || gender === '女生') gender = '女'
    else if (typeof gender === 'string' && gender.includes('男')) gender = '男'
    else if (typeof gender === 'string' && gender.includes('女')) gender = '女'
    else gender = '男'
    editForm.value = { ...JSON.parse(JSON.stringify(row)), gender }
    isEdit.value = true
    dialogVisible.value = true
}
const onSelectionChange = (val) => {
    multipleSelection.value = val
}
const onPageChange = (page) => {
    currentPage.value = page
}
const onPageSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
}
const onBatchDelete = async () => {
    if (multipleSelection.value.length === 0) return
    const notDeletable = multipleSelection.value.filter(row => row.status !== '正常')
    if (notDeletable.length > 0) {
        ElMessage.error('只能批量删除“正常”状态的读者')
        return
    }
    try {
        await ElMessageBox.confirm(`确定要删除选中的${multipleSelection.value.length}位读者吗？`, '批量删除', { type: 'warning' })
        for (const row of multipleSelection.value) {
            await axios.delete(`/readers/${row.id}`)
        }
        ElMessage.success('批量删除成功')
        fetchReaders(search.value)
        if (readerTable.value) readerTable.value.clearSelection()
    } catch (e) {
        ElMessage.error('批量删除失败')
    }
}
const onSave = async () => {
    // 表单校验
    if (!editForm.value.name || !editForm.value.username || !editForm.value.phone) {
        ElMessage.error('请填写完整信息')
        return
    }
    if (!/^1[3-9]\d{9}$/.test(editForm.value.phone)) {
        ElMessage.error('手机号格式不正确')
        return
    }
    if (!isEdit.value && !editForm.value.password) {
        ElMessage.error('请填写密码')
        return
    }
    // 保证role字段始终为'reader'
    editForm.value.role = 'reader'
    try {
        if (isEdit.value && !editForm.value.password) {
            delete editForm.value.password // 编辑时未填写密码则不传
        }
        if (editForm.value.id) {
            await axios.put(`/readers/${editForm.value.id}`, editForm.value)
            ElMessage.success('编辑成功')
        } else {
            await axios.post('/readers', editForm.value)
            ElMessage.success('新增成功')
        }
        dialogVisible.value = false
        fetchReaders(search.value) // 保存后立即刷新表格
    } catch (e) {
        ElMessage.error('保存失败')
    }
}
const onDelete = async (row) => {
    // 前端先判断该读者是否有借阅记录
    try {
        const res = await axios.get(`/borrow-records?userId=${row.id}`)
        if (res.data && res.data.length > 0) {
            ElMessage.error('该读者有借阅记录，无法删除')
            return
        }
    } catch (e) {
        // 如果接口异常，允许后端兜底
    }
    try {
        await axios.delete(`/readers/${row.id}`)
        ElMessage.success('删除成功')
        fetchReaders(search.value)
    } catch (e) {
        if (e.response && e.response.data && e.response.data.message && e.response.data.message.includes('借阅记录')) {
            ElMessage.error('该读者有借阅记录，无法删除')
        } else {
            ElMessage.error('删除失败')
        }
    }
}
</script>

<style scoped>
.reader-manage {
    padding: 24px;
}

.toolbar {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
}
</style>
